define([
  'vue',
  'text!' + ELMP.resource('components/member-list/index.html', 'tmzk_workflow'),
  'css!' + ELMP.resource('components/member-list/index.css', 'tmzk_workflow'),
  ELMP.resource('index.js', 'workflow_sdk'),
  ELMP.resource('components/vue-collapse/index.js', 'lib')
], function (Vue, template, css, WorkflowSdk, vueCollapse) {
  return {
    components: {
      vueCollapse
    },
    template,
    props: {
      processInfo: {
        type: Object,
        default: {}
      },
      businessKey: { type: String, default: '' },
      header: { type: String, default: '成员' },
      handleRow: {
        // 用于自定义处理行数据,当触发updateData更新表格展示时会触发,返回值表示改行是否展示
        type: Function,
        default: () => true
      }
    },

    watch: {
      processInfo: {
        handler (newValue) {
          // 审批页面回显
          this.fetchProcessInstanceNodes(newValue).then((data, users) => {
            const nodeList = this.handleNodeData(data, 'steps')
            this.handleMember(nodeList, 'steps')
          })
        },
        deep: true
      }
    },
    data () {
      return {
        userInfo: [],
        nodeInfo: null,
        memberList: []
      }
    },
    mounted () {
      if (this.businessKey !== '') {
        // 启动页面回显
        this.fetchGetNodeInfo(this.businessKey).then((data) => {
          const nodeList = this.handleNodeData(data, 'start')
          this.handleMember(nodeList, 'start')
        })
      }
    },
    methods: {
      getTableData (isDraft, allValid = false) {
        const that = this
        return new Promise((r, j) => {
          if (isDraft) {
            r(that.memberList)
          } else {
            if (that.validFun(allValid)) {
              r(that.memberList)
            } else {
              j()
            }
          }
        })
      },
      // 设置成员
      setTableData (list) {
        this.memberList = list
        this.mapRenderMember(list)
      },
      //   验证
      validFun (allValid) {
        let isValid = true
        for (let index = 0; index < this.memberList.length; index++) {
          const c = this.memberList[index]
          const validate = c.validate
          if (validate) {
            if (validate(c)) {
              continue
            } else {
              return false
            }
          }
          if (allValid) { // 验证全部节点
            if (c.userInfo.length <= 0 && c.nodeName !== '专家会签') {
              $.msg.tips(`"${c.nodeName}"流程节点审批人不能为空!`)
              isValid = false
              return false
            }
          } else { // 验证第一个个节点
            if (index === 0 && c.nodeName == '重新提交') {
              if (this.memberList[1].userInfo.length <= 0) {
                $.msg.tips(`"${this.memberList[1].nodeName}"流程节点审批人不能为空!`)
                isValid = false
                return false
              }
            }
            if (index === 0 && c.userInfo.length <= 0) {
              $.msg.tips(`"${c.nodeName}"流程节点审批人不能为空!`)
              isValid = false
              return false
            }
          }
        }
        return isValid
      },
      // 获取流程节点数据
      fetchGetNodeInfo (businessKey) {
        return new Promise((resolve, reject) => {
          $.el
            .get({
              url: ELMP.url(
                '/workflow/v1/procinst/{0}/nodes/lastversion/DRAFT',
                businessKey
              )
            })
            .then((res) => {
              if (res.code === '200') {
                resolve(Object.assign(JSON.parse(res.res.data), { users: res.res.users }))
              } else {
                reject()
              }
            })
        })
      },
      // 获取流程实例节点信息
      fetchProcessInstanceNodes (processInfo) {
        return new Promise((resolve, reject) => {
          $.el
            .get({
              url: ELMP.url(
                '/workflow/v1/procinst/{0}/nodes', processInfo.processDefinitionId
              ),
              data: {
                processInstanceId: processInfo.processInstanceId
              }
            })
            .then((res) => {
              if (res.code === '200') {
                this.userInfo = res.res.users
                resolve(JSON.parse(res.res.data))
              } else {
                reject()
              }
            })
        })
      },
      // 处理流程节点数据
      handleNodeData (nodeData, fage) {
        const that = this
        const nodeList = []
        let obj = null
        nodeData.activities && nodeData.activities.forEach(function (item, index) {
          if (item.properties.type == 'startEvent') {
            startObj = {
              // nogo, going, gone
              serialnumber: '',
              type: 'going',
              rolekey: item.properties.rolekey,
              activityId: item.activityId,
              arr: [
                {
                  active: 'going',
                  activityId: 'startEvent',
                  flowState: undefined,
                  id: item.activityId,
                  serialnumber: '',
                  text: '开始',
                  type: 'going',
                  url: ''
                }
              ]
            }
          } else if (item.properties.type == 'endEvent') {
            endObj = {
              // nogo, going, gone
              serialnumber: '',
              type: 'nogo',
              rolekey: item.properties.rolekey,
              activityId: item.activityId,
              arr: [
                {
                  active: 'nogo',
                  activityId: 'endEvent',
                  flowState: undefined,
                  id: item.activityId,
                  serialnumber: '',
                  text: '结束',
                  type: 'nogo',
                  url: ''
                }
              ]
            }
          } else if (item.properties.type == 'userTask') {
            obj = {
              // nogo, going, gone
              serialNumber: parseInt(item.properties.serialnumber),
              type: 'nogo',
              rolekey: item.properties.rolekey,
              activityId: item.activityId,
              arr: [
                {
                  active: 'nogo',
                  activityId: item.properties.type,
                  flowState: undefined,
                  id: item.activityId,
                  serialnumber: '',
                  text: item.properties.name,
                  type: 'nogo',
                  url: '',
                  candidateUsers: item.candidateUsers || '',
                  nodeUsers: item?.candidateUsers ? that.handleUserInfo(nodeData.users = [], item.candidateUsers) : []
                }
              ]
            }
            nodeList.push(obj)
          }
        })
        this.serialArr(nodeList, 'serialNumber')
        nodeList.unshift(startObj)
        nodeList.push(endObj)

        return nodeList
      },
      // 节点冒泡排序
      serialArr (arr, key) {
        let temp = ''
        for (let i = 0; i < arr.length; i++) {
          for (let j = i; j < arr.length; j++) {
            if (parseInt(arr[i][key]) > parseInt(arr[j][key])) {
              temp = arr[i]
              arr[i] = arr[j]
              arr[j] = temp
            }
          }
        }
      },
      //   处理成成员table表格数据
      handleMember (nodeList, fage) {
        const arr = nodeList.filter((c) => c.serialnumber !== '')
        if (fage === 'start') {
          this.memberList = arr.map((c) => {
            let rowData = {}
            if (c.arr[0].candidateUsers === '${startUserId}') { // 如果节点是配置的发起人
              rowData = Object.assign(rowData, {
                isStartUserId: true,
                nodeName: c.arr[0].text,
                nodeId: c.activityId,
                userInfo: [$.el.auth.user],
                userId: $.el.auth.user.id,
                disabled: true,
                multiple: 0 // 0多选 1单选
              })
            } else {
              rowData = Object.assign(rowData, {
                isStartUserId: false,
                nodeName: c.arr[0].text,
                nodeId: c.activityId,
                userInfo: c.arr[0].nodeUsers,
                userId: c.arr[0].candidateUsers,
                disabled: false,
                multiple: 0 // 0多选 1单选
              })
            }
            return rowData
          })
        } else {
          this.memberList = arr.map((c) => {
            const users = this.handleUserInfo(this.userInfo, c.arr[0].candidateUsers)
            const rowData = {
              nodeName: c.arr[0].text,
              nodeId: c.activityId,
              userInfo: users,
              userId: ids.join(','),
              disabled: false,
              multiple: 0 // 0多选 1单选
            }
            return rowData
          })
        }
        console.log(this.memberList, 'nodeList')

        this.mapRenderMember(this.memberList)
      },
      // 处理人员信息    userId和userInfo
      handleUserInfo (users, ids) {
        ids = ids.split(',')
        const userInfos = []
        users.forEach(c1 => {
          ids.forEach(c2 => {
            if (c1.id === c2) {
              userInfos.push(c1)
            }
          })
        })
        return userInfos
      },
      // 循环渲染表格选人
      mapRenderMember (list) {
        const that = this
        list.forEach((c) => {
          if (that.handleRow(c)) {
            const obj = {}
            c.userInfo = c.userInfo.reduce((n, c) => {
              obj[c.id] ? '' : (obj[c.id] = true && n.push(c))
              return n
            }, [])
            that.$nextTick(() => {
              that.renderMember(c.nodeId, c.userInfo, c.multiple, c.disabled)
            })
          }
        })
      },
      // 渲染选人组件
      renderMember (className, arr = [], multiple = 1, disabled = false) {
        const that = this
        $(`.${className}`).selectMember({
          members: arr,
          key: 'id',
          showAll: true,
          disabled,
          multiple,
          panel: [
            {
              title: $.i18n.get('people_info'), // '人员信息'
              url: ELMP.url('/org/v1/users/fuzzy'),
              // 接口参数
              data: function (params, type) {
                return {
                  fuzzyQueryCondition: params.term
                }
              },
              search: true,
              // 对查询出的数据的处理
              process: function (res) {
                return res.res.data.records
              }
            }
          ],
          onComplete: function (ids, members) {
            that.memberList.forEach((c) => {
              if (c.nodeId === className) {
                WorkflowSdk.setApproveUser(c.nodeId, members)
                c = Object.assign(c, {
                  userId: ids.join(','),
                  userInfo: members
                })
              }
            })
            that.mapRenderMember(that.memberList)
          }
        })
      }
    }
  }
})
